﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PFMCandidate;

namespace PFMHandlers
{
    public class PFMDecodeHandler:PFMHandler
    {
        private static string sEncodeCode = "POODlwCSharp";

		public PFMDecodeHandler()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public override byte[] Perform(Candidate aCandidate, byte[] baTarget)
		{

			byte[] sResult = null;
    
			base.Perform(aCandidate, baTarget);
            sResult = GetProcessingData(aCandidate, baTarget);
            ChangeCandidateProcessedName(aCandidate);  
			sResult = DoDecodeData(aCandidate, sResult);            
			return sResult;
		} 
   
		private byte[] DoDecodeData(Candidate aCandidate, byte[] sResult)
		{
			PFMUnZipHandler aHandler = null;
			int iCodeLength = sEncodeCode.Length;
			for (int iCount = 0; iCount < sResult.Length - 1; iCount++) 
			{
				sResult[iCount] = (byte) (sResult[iCount] ^ (byte) sEncodeCode[iCount % iCodeLength]);
			}
			aHandler = new PFMUnZipHandler();
			sResult = aHandler.Perform(aCandidate, sResult);

			return sResult;
		}
        protected override void ChangeCandidateProcessedName(PFMCandidate.Candidate aCandidate)
        {
            //throw new NotImplementedException();
            //Candidate.ProcessedName = aCandidate.Name;
            base.ChangeCandidateProcessedName(aCandidate);
            if (aCandidate.ProcessedName.EndsWith(".XOR",StringComparison.CurrentCultureIgnoreCase))
              aCandidate.ProcessedName = aCandidate.ProcessedName.Remove(aCandidate.ProcessedName.Length - 4);
        }
    }
}
